import io
import os
from typing import Union

import uvicorn
from paddleocr import PaddleOCR
import numpy as np
from fastapi import FastAPI, UploadFile, Form
from PIL import Image, ImageGrab

# 打包
# nuitka --mingw64 --show-progress --standalone --onefile --include-data-dir=./config=config --include-data-dir=./paddleocr=paddleocr  server.py

current_dir = os.path.dirname(os.path.abspath(__file__))
ocr = PaddleOCR(use_angle_cls=True,
                show_log=False,
                det_model_dir = os.path.join(current_dir, 'config','ch_PP-OCRv4_det_server_infer'),
                rec_model_dir = os.path.join(current_dir, 'config','ch_PP-OCRv4_rec_infer'),
                cls_model_dir = os.path.join(current_dir, 'config','ch_ppocr_mobile_v2.0_cls_infer'),
                )
app = FastAPI()

@app.post('/getOcr')
async def getOcr(
    x1: int = Form(0),
    y1: int = Form(0),
    x2: int = Form(0),
    y2: int = Form(0),
    file: Union[UploadFile, None] = None,
    type: int = Form(0)):
    if type == 1:
        screen = Image.open(io.BytesIO(await file.read()))
        screen = np.array(screen)
    else:
        screen = np.array(ImageGrab.grab(bbox=(x1, y1, x2, y2)))[:, :, ::-1]  # 假设屏幕分辨率为 1920x1080

    # _, img_encoded = cv2.imencode('.jpg', screen)  # 需要导入 cv2
    # 保存
    # cv2.imwrite(f'screenshot.jpg', screen)
    # screenshot_count += 1
    # 发送包含文件的 POST 请求
    result = ocr.ocr(screen, cls=True)
    if len(result) == 0:
        return ""
    return result[0]

if __name__ == '__main__':
    print("启动成功...^_^...监听端口：9236")
    uvicorn.run(app, host="127.0.0.1", port=9236, log_level="critical", workers=1)